import React, { Component } from 'react';
import {
    Button, Form, Radio, Checkbox, Input, Select, Icon, message, Spin,Modal,Row, Col
} from 'antd';
import { connect } from 'dva';
import InputText from '@/components/Input/index';
import Preview from './preview';
import styles from './index.less';
import SelectedImage from '@/components/plugins/selectImage/index';
import { ColorPicker } from 'zent';
import GrantCondRange from './grantCondRang';
import router from 'umi/router';
const { TextArea } = Input;
const Option = Select.Option;
const confirm = Modal.confirm;
let id = 0;

@connect(({global, cards, loading}) => ({
    oemInfo: global.oemInfo,
    cards,
    loading1: loading.effects['gradeCard/FindLevelCardById'],
}))

class EditCards extends Component {
    constructor() {
        super();
        this.state= {
            btnLoading: false,
            btnLoading2: false,
            startLoading: true,
            color: '#FF2E2E',//颜色
            BackType: 1,
            name: '', // 名称
            checkbox: [],//权益
            memberLevel: '一',
            discount: '',//折扣
            discountDisable: false,
            pointsDisable: false,
            couponsDisable: true,
            errorData: {},
            cardGrantCond: [0,0,0],
            cardsArr:[],
            couponArr:[
                {
                    CouponId:'',
                    Num:''
                }
            ]
        }
    }
    componentWillMount() {
      window.Isoption = false;
    }

    componentDidMount() {
      window.Isoption = true;
        this.findLevelCardById();
        this.findLevelList();
        this.getCouponList()
    }

    // 获取等级
    findLevelList =() => {
        const { dispatch, match} = this.props;
        dispatch({
            type: 'gradeCard/FindLevelList',
            payload: {
                Id: match.params.id/1
            },
            callBack: {
                success: res => {
                    if(res.Code===0) {
                        this.setState({
                            levelList: res.Data
                        })
                    }
                },
                error: res => {
                    message.error(res.Msg);
                }
            }
        })
    }

    getCouponList=()=> {
        const { dispatch } = this.props;
        dispatch({
            type: 'gradeCard/GetCouponList',
            callBack: {
                success: res => {
                    if(res.Code===0) {
                        this.setState({
                            cardsArr: res.Data?res.Data:[]
                        })
                    }
                },
                errpr: res => {
                    message.error(res.Msg);
                }
            }
        })
    }

    remove = (k) => {
        const {couponArr}= this.state;
        couponArr.splice(k, 1);
        this.setState({
            couponArr
        })
      }

      add = () => {
        const {couponArr}= this.state;
        let arr=JSON.parse(JSON.stringify(couponArr))
        arr.push({
            CouponId:'',
            Num:''
        })
        this.setState({
            couponArr:arr
        })
      }

      selectChange=(value, index)=> {
        const {couponArr}= this.state;
        let arr=JSON.parse(JSON.stringify(couponArr))
        arr[index].CouponId = value
      this.setState({
          couponArr:arr
      })
    }

    inputChange=(e, index)=> {
        const {couponArr}= this.state;
        let arr=JSON.parse(JSON.stringify(couponArr))
        arr[index].Num = e.target.value;
        this.setState({
            couponArr:arr
        })
    }

      //根据ID获取编辑数据
      findLevelCardById =() => {
        const { dispatch, match } = this.props;
        this.setState({
            id: match.params.id ? match.params.id / 1 : 0
        },() => {
            dispatch({
               type: 'gradeCard/FindLevelCardById',
               payload: {
                   id: this.state.id
               },
               callBack: {
                   success: res => {
                       this.setState({
                        startLoading: false,
                        BackType: res.Data.BackType, //卡片封面类型
                        color: res.Data.BackColor, //背景色
                        imageUrl: res.Data.BackImgPath, //背景图
                        width: res.Data.BackImgWidth, //宽度
                        height: res.Data.BackImgHeight, //高度
                        name: res.Data.Name, // 会员卡名称
                        couponsDisable: res.Data.HasRightsCoupons?false: true,
                        HasRightsPostage: res.Data.HasRightsPostage, //是否具有包邮权益
                        HasRightsDiscount: res.Data.HasRightsDiscount, //是否具有折扣权益
                        discount: res.Data.Discount, //折扣值
                        HasRightsPoint: res.Data.HasRightsPoint, //是否具有积分权益
                        Points: res.Data.Points, //积分值
                        HasRightsCoupons: res.Data.HasRightsCoupons, //是否具有优惠券权益
                        checkbox: [
                          res.Data.HasRightsPostage&& '1',
                          res.Data.HasRightsDiscount&&'2',
                          res.Data.HasRightsPoint&&'3',
                          res.Data.HasRightsCoupons&& '4'
                        ],
                        cardGrantCond: [
                            res.Data.CardGrantCond.TradeLimit,
                            res.Data.CardGrantCond.AmountLimit,
                            res.Data.CardGrantCond.PointsLimit
                        ],
                        couponArr: res.Data.Coupons&&res.Data.Coupons.length> 0?res.Data.Coupons:[
                            {
                                CouponId:'',
                                Num:''
                            }
                        ],
                        Description: res.Data.Description, //使用须知
                        ServicePhone: res.Data.ServicePhone, //客服电话
                        memberLevel: res.Data.Level, //等级
                       })
                   },
                   error: res => {
                       message.error(res.Msg);
                   }
               }
            })
        })
      }

    handleChangeColor =(color) => {
        this.setState({
            color
          });
    }

    handleChangeRadio =(e) => {
        this.setState({
            BackType: e.target.value
        })
    }

    selectLevel =(value) => {
        this.setState({
            memberLevel: value
        })
    }

  // 添加图片
  handleAdd = () => {
    this.OpenImageModal();
  }

    // 修改名称
    onTextChange = (v) => {
        this.setState({ name: v.target.value  });
        this.props.form.setFieldsValue({
          name: v.target.value
        })
      }

   // 校验名
  checkName = (e) => {
    this.props.form.validateFields(['name'], { force: true });
  }

  handleClickCheckbox =(value) => {
      this.setState({
          checkbox: value
      })
      if(!(value.indexOf('2')> -1)) {
        this.props.form.setFieldsValue({
            discount: ''
        })
        this.setState({
            discount: '',
            discountDisable: true
        })
      }else {
          this.setState({
            discountDisable: false
          })
      }
      if(!(value.indexOf('3')> -1)) {
        this.props.form.setFieldsValue({
            points: ''
        })
        this.setState({
            points: '',
            pointsDisable: true
        })
      }else {
          this.setState({
            pointsDisable: false
          })
      }
      if(!(value.indexOf('4')> -1)) {
        this.setState({
            couponsDisable: true,
            couponArr: [
                {
                    CouponId:'',
                    Num:''
                }
            ]
        })
      }else {
          this.setState({
            couponsDisable: false,
          })
      }
  }

  //折扣
  onChangeDiscount =(e) => {
      this.setState({
        discount: e.target.value
      })
  }

     // 图片插件
  imgModal = ref => {
    this.imgmodal = ref;
  };
  OpenImageModal = () => {
    this.imgmodal.handleShowModal();
  };
  onImageChange = res => {
    this.setState({
      imageUrl: res.imageUrl.substr(res.imageUrl.indexOf('.com/') + 5),
      width: res.width,
      height: res.height
    });
    this.props.form.setFieldsValue({
        url: res.imageUrl.substr(res.imageUrl.indexOf('.com/') + 5)
    });
    this.imgmodal.handleModalVisible();
  };

  // 取消
  clickCancel =() => {
    router.replace({
        pathname: `/${window.storeId}/customer/card`,
    });
  }

   //删除
   clickDelete =() => {
    const {dispatch} = this.props;
    const that = this;
    confirm({
        title:"删除",
        content:"确认删除?",
        okText: '确认',
        cancelText:'取消',
        onOk() {
            dispatch({
                type: 'gradeCard/DelLevelCard',
                payload: {
                    Id: that.state.id,
                },
                callBack: {
                    success: res=> {
                        that.setState({ btnLoading2: false });
                        message.success('删除成功');
                        router.replace({
                            pathname: `/${window.storeId}/customer/card`,
                        });
                    },
                    error: res=> {
                        that.setState({ btnLoading2: false });
                        message.error(res.Msg);
                    }
                }
            })
        },
        onCancel() {}
    })
  }

  //提交
  handleSubmit =(e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll({force: true}, (err, values) => {
        if(!err) {
            this.setState({ btnLoading: true });
            const {dispatch} = this.props;
            const { couponArr } = this.state;
            couponArr.forEach(item=>{
                item.Num=item.count?item.count-0:0;
                item.CouponId=item.Id?item.Id:0;
                delete item.Id;
                delete item.StoreId;
                delete item.CardId
            })
            dispatch({
                type: 'gradeCard/UpdateLevelCard',
                payload: {
                    Id: this.state.id,
                    BackType: values.BackType, //卡片封面类型
                    BackColor: this.state.color, //背景色
                    BackImgPath: this.state.imageUrl, //背景图
                    BackImgWidth: this.state.width, //宽度
                    BackImgHeight: this.state.height, //高度
                    Name: values.name, // 会员卡名称

                    HasRightsPostage: values.memberCoupon.indexOf('1')> -1, //是否具有包邮权益
                    HasRightsDiscount: values.memberCoupon.indexOf('2')> -1, //是否具有折扣权益
                    Discount: values.discount, //折扣值
                    HasRightsPoint: values.memberCoupon.indexOf('3')> -1, //是否具有积分权益
                    Points: values.points, //积分值
                    HasRightsCoupons: values.memberCoupon.indexOf('4')> -1, //是否具有优惠券权益
                    Coupons: couponArr, //暂无优惠券

                    Description: values.description, //使用须知
                    ServicePhone: values.servicePhone, //客服电话

                    CardGrantCond: {  //领取设置
                        TradeLimit: values.cardGrantCond?parseInt(values.cardGrantCond[0]): 0, //累计成功支付笔数
                        AmountLimit: values.cardGrantCond?parseFloat(values.cardGrantCond[1]): 0, //累计消费金额
                        PointsLimit: values.cardGrantCond?parseInt(values.cardGrantCond[2]): 0,  //累计积分
                    },
                    Level: values.level, //等级
                },
                callBack: {
                    success: res => {
                        this.setState({ btnLoading: false });
                        message.success('保存成功');
                        router.replace({
                            pathname: `/${window.storeId}/customer/card`,
                        });
                    },
                    error: res => {
                      this.setState({ btnLoading: false });
                      if(res.Code=== 30003) {
                        message.error(res.Msg);
                        this.setState({
                          errorData: res.Data
                        })
                      } else {
                        message.error(res.Msg)
                      }
                    }
                }
            });
        } else {
            this.setState({ btnLoading: false });
        }
    });
  }

    //店铺信息
    clickStore=() => {
        router.replace({
            pathname: `/${window.storeId}/store/info`
        })
      }

    render() {
        // console.log(this.props.oemInfo);
        const {oemInfo, loading1} = this.props;
        const { color, imageUrl, BackType, name, checkbox, btnLoading, btnLoading2,
            memberLevel, width, height, discount, Points, Description, ServicePhone, memberLevelValue,cardGrantCond,
            discountDisable,pointsDisable, levelList,errorData,couponArr, cardsArr,couponsDisable,startLoading
        } = this.state;
        const { getFieldDecorator, getFieldValue} = this.props.form;
          const formItems = couponArr.map((k, index) => (
            <Form.Item
                required={false}
                key={index}
                className={styles.addItem}
                style={index===0?{marginBottom: 0}: {marginBottom: 16}}
          >
            {getFieldDecorator(`Coupons[${k.Id}]`, {
              validateTrigger: 'onBlur',
              rules: [{required: false,whitespace: true}],
            })(
                <div style={{display: 'flex'}}>
                  <Select
                      placeholder="请选择"
                      style={{width: 126,marginRight: 8}}
                      value={k.CouponId}
                      disabled={couponsDisable}
                      onChange={(value)=> this.selectChange(value, index)}
                  >
                      {cardsArr&&cardsArr.map((item, index) => {
                          return (
                              <Option value={item.Id} key={index}>{item.Name}</Option>
                          )
                      })}
                  </Select>
                  <Input
                      style={{width: 126, height: 32, marginRight: 8}}
                      addonAfter="张"
                      value={k.Num}
                      onChange={(value)=> this.inputChange(value, index)}
                      disabled={couponsDisable}
                  />
                </div>
            )}
            {couponArr.length > 0 ? (
                index===0?(!couponsDisable &&couponArr.length<10 && <a onClick={this.add}>添加</a>):
              (<Icon
                className="dynamic-delete-button"
                type="minus-circle-o"
                onClick={() => this.remove(index)}
              />
            ) ):null
            }
          </Form.Item>
          ));
        const colorStyle={
            '#FF2E2E': '#FF6D6D',
            '#FF752E': '#FFA76D',
            '#FFB92E': '#FFCE6D',
            '#E6DF00': '#EBEA8C',
            '#0BD9D2': '#7EE5E2',
            '#19BE86': '#4FD9AA',
            '#2E74FF': '#6D9EFF',
            '#7274FF': '#726DFF',
            '#742EFF': '#9E6DFF',
            '#FF2E97': '#FF6DB6'
        };
        const presetColors = [
            '#FF2E2E',
            '#FF752E',
            '#FFB92E',
            '#E6DF00',
            '#0BD9D2',
            '#19BE86',
            '#2E74FF',
            '#7274FF',
            '#742EFF',
            '#FF2E97'
        ];
        const leftColor = colorStyle[color];
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: { span: 18 },
        };
        const formItemLayout1 = {
            labelCol: {span: 5},
            wrapperCol: { span: 10 },
        };
        const formItemLayout2 = {
            labelCol: {span: 5},
            wrapperCol: { span: 19 },
        };
        return (
            <Form className={styles.contentBox} onSubmit={this.handleSubmit}>
                <SelectedImage onRef={this.imgModal} selectImage={this.onImageChange} />
                <Spin spinning={startLoading}>
                    <div className={styles.body}>

                        <Preview
                            title={'会员卡'}
                            backgroundColor={color}
                            leftColor={leftColor}
                            oemInfo={oemInfo}
                            memberLogo={oemInfo.storeLogo}
                            memberName={oemInfo.storeName}
                            imageUrl={imageUrl}
                            BackType={BackType}
                            memberLevel={memberLevel}
                            cardName={name}
                            width={width}
                            height={height}
                            checkbox={checkbox}
                            discount={discount}
                        />
                        <div className={styles.form}>
                                <div className={styles.itemTitle}>基本信息</div>
                                <Form.Item
                                    label="店铺名称"
                                    {...formItemLayout}
                                >
                                  <span>{oemInfo.storeName}</span>
                                </Form.Item>
                                <Form.Item
                                    label="店铺logo"
                                    extra={(
                                        <span>如需修改店铺信息，请在<a onClick={this.clickStore}>店铺信息</a>中更新</span>
                                    )}
                                    {...formItemLayout}
                                >
                                    <span className={styles.logoImg}>
                                        <img src={oemInfo&&oemInfo.cdnUrl?oemInfo['cdnUrl'] + '/' + oemInfo.storeLogo +'?x-oss-process=style/240':''} />
                                    </span>
                                </Form.Item>
                                <Form.Item
                                    label="卡片封面"
                                    {...formItemLayout}
                                    extra="尺寸900*400像素，小于1M，支持jpg、png、jpeg格式"
                                >
                                    {getFieldDecorator('BackType', {
                                        initialValue: BackType
                                    })(
                                        <Radio.Group onChange={this.handleChangeRadio}>
                                            <Radio value={1}>
                                                背景色
                                            </Radio>
                                            <ColorPicker
                                                color={color}
                                                type="simple"
                                                onChange={this.handleChangeColor}
                                                presetColors={presetColors}
                                            />
                                            <br/>
                                            <Radio value={2}>
                                                封面图片
                                            </Radio>
                                            <a onClick={this.handleAdd}>选择图片</a>
                                        </Radio.Group>
                                    )}
                                 </Form.Item>
                                 <Form.Item
                                    label="会员卡名称"
                                    {...formItemLayout1}
                                 >
                                    {getFieldDecorator('name', {
                                        initialValue: name,
                                        rules: [{
                                            required: true, message: '会员卡名称必须填写，最多9个字',
                                        }]
                                    })(
                                        <InputText name="name" onChange={this.onTextChange} onBlur={this.checkName} showtotal maxLength={9} />
                                    ) }
                                 </Form.Item>
                                 <Form.Item
                                    label="会员权益"
                                    {...formItemLayout}
                                 >
                                    {getFieldDecorator('memberCoupon', {
                                        initialValue: checkbox,
                                        rules: [{
                                            required: true, message: '会员权益最少一项'
                                        }]
                                    })(
                                        <Checkbox.Group onChange={this.handleClickCheckbox}>
                                        <Checkbox value="1">包邮</Checkbox><br/>
                                        <div style={{marginTop: 8}}>
                                            <Row>
                                                <Col span={7} style={{marginTop: 8}}><Checkbox value="2">会员折扣</Checkbox></Col>
                                                <Col span={16}>
                                                    <Form.Item
                                                        extra={
                                                            <span style={{marginLeft: -104}}>请填写0.1~9.9之间的数字，保留一位小数</span>
                                                        }
                                                        style={{marginBottom: 0}}
                                                    >
                                                        {getFieldDecorator('discount', {
                                                            initialValue: discount,
                                                            rules: [
                                                                {required: checkbox.indexOf('2')> -1, message: '请填写会员折扣'},
                                                                {pattern: /^(?=0\.[1-9]|[1-9]\.\d).{3}$|^([1-9])$/, message:'0.1~9.9之间的数字'}
                                                        ]
                                                        })(
                                                            <Input
                                                                name="discount"
                                                                style={{width: 126, height: 32}}
                                                                addonAfter="折"
                                                                onChange={this.onChangeDiscount}
                                                                disabled={discountDisable}
                                                                onBlur={this.checkdDiscount}
                                                            />
                                                        )}
                                                    </Form.Item>
                                                </Col>
                                            </Row>
                                        </div>
                                        <div style={{marginTop: 8}}>
                                            <Row>
                                                <Col span={7} style={{marginTop: 8}}><Checkbox value="3">领卡即送积分</Checkbox></Col>
                                                <Col span={16}>
                                                    <Form.Item
                                                        extra={
                                                            <span style={{marginLeft: -104}}>请填写1~99999之间的整数</span>
                                                        }
                                                        style={{marginBottom: 0}}
                                                    >
                                                    {getFieldDecorator('points', {
                                                        initialValue: Points,
                                                        rules: [
                                                            {required: checkbox.indexOf('3')> -1, message: '请填写积分值'},
                                                            {pattern: /^\+?[1-9]\d{0,4}?$/, message:'1~99999之间的整数'}
                                                        ]
                                                    })(
                                                        <Input
                                                            name="points"
                                                            style={{width: 126, height: 32}}
                                                            addonAfter="分"
                                                            disabled={pointsDisable}
                                                            onBlur={this.checkdPoints}
                                                        />
                                                    )}
                                                    </Form.Item>
                                                </Col>
                                            </Row>
                                        </div>
                                        <div style={{marginTop: 8}}>
                                            <div>
                                                <Row>
                                                    <Col span={7} style={{marginTop: 8}}>
                                                        <Checkbox value="4">领卡送优惠券</Checkbox>
                                                    </Col>
                                                    <Col span={17}>
                                                        {formItems}
                                                    </Col>
                                                </Row>
                                            </div>
                                            <div className={styles.formItemsFoot}>最多选择10张优惠券，优惠券过期、被删除、或剩余数量为0时，系
                                                统不再送券
                                            </div>
                                        </div>
                                    </Checkbox.Group>
                                    )}
                                 </Form.Item>
                                 <Form.Item
                                    label="使用须知"
                                    {...formItemLayout}
                                 >
                                    {getFieldDecorator('description', {
                                        initialValue: Description,
                                        rules: [{
                                            // required: true, message: '使用须知必须填写'
                                        }]
                                    })(
                                        <TextArea
                                            rows={3}
                                            placeholder="可填写其他补充信息以便会员知晓，最多可输入300个字符"
                                            maxLength={300}
                                        />
                                    )}
                                 </Form.Item>
                                 <Form.Item
                                    label="客服电话"
                                    {...formItemLayout1}
                                 >
                                    {getFieldDecorator('servicePhone', {
                                        initialValue: ServicePhone,
                                        rules: [
                                            {required: true, message: '客服电话必须填写'},
                                            {pattern: /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确格式'}
                                    ]})(
                                        <Input placeholder="请输入手机号或固定电话"/>
                                    )}
                                 </Form.Item>
                                 <div className={styles.itemTitle2}>领取设置</div>
                                 <Form.Item
                                    label="升级条件"
                                    {...formItemLayout2}
                                    extra="升级条件将以完成的订单作为判断依据"
                                 >
                                    {getFieldDecorator('cardGrantCond', {
                                        initialValue: cardGrantCond,
                                        rules: [{
                                            required: false,
                                        }]
                                    })(
                                        <GrantCondRange errorData={errorData}/>
                                    )}
                                 </Form.Item>
                                 <Form.Item
                                    label="等级"
                                    {...formItemLayout2}
                                    extra="数字越大等级越高，当会员满足相应条件时会自动发放对应等级的会员卡"
                                 >
                                    {getFieldDecorator('level', {
                                        initialValue:  memberLevel,
                                        rules: [{
                                            required: true, message: '等级必须选择'
                                        }]
                                    })(
                                        <Select placeholder="请选择" style={{width: 126}} onChange={this.selectLevel}>
                                            {levelList&& levelList.map((item, index) => {
                                                return <Option value={item} key={index}>{item}</Option>
                                            })}
                                        </Select>
                                    )}
                                 </Form.Item>
                        </div>
                    </div>
                    </Spin>
                    <div className="xkd-bottom-actions">
                        <Button className="xkd-mr8" onClick={this.clickCancel}>
                             取消
                        </Button>
                        <Button
                            className="xkd-mr8"
                            type="danger"
                            loading={btnLoading2}
                            onClick={this.clickDelete}
                        >
                            删除
                        </Button>
                        <Button
                            htmlType="submit"
                            type="primary"
                            loading={btnLoading}
                        >
                            保存
                        </Button>
                    </div>
            </Form>
        )
    }
}

export default Form.create()(EditCards);
